package com.duofan.gmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.duofan.gmall.common.utils.R;
import com.duofan.gmall.product.entity.SkuImagesEntity;
import com.duofan.gmall.product.entity.SpuInfoDescEntity;
import com.duofan.gmall.product.feign.SeckillFeignService;
import com.duofan.gmall.product.service.*;
import com.duofan.gmall.product.vo.SeckillSkuInfoVo;
import com.duofan.gmall.product.vo.SkuItemSaleAttrsVo;
import com.duofan.gmall.product.vo.SkuItemVo;
import com.duofan.gmall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duofan.gmall.common.utils.PageUtils;
import com.duofan.gmall.common.utils.Query;

import com.duofan.gmall.product.dao.SkuInfoDao;
import com.duofan.gmall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        // key:
        //catelogId: 0
        //brandId: 0
        //min: 0
        //max: 0
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        String catelogId = (String)params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String)params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String)params.get("min");
        if(!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }
        String max = (String)params.get("max");
        if(!StringUtils.isEmpty(max) && !"0".equalsIgnoreCase(max)) {
            wrapper.le("price", max);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1 sku基本信息 pms_sku_info
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> saleAttrsFuture = infoFuture.thenAcceptAsync((info) -> {
            // 3 spu销售属性组合
            List<SkuItemSaleAttrsVo> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(info.getSpuId());
            skuItemVo.setSaleAttrs(saleAttrs);
        }, executor);

        CompletableFuture<Void> spuInfoFuture = infoFuture.thenAcceptAsync((info) -> {
            // 4 spu介绍
            SpuInfoDescEntity spuInfo = spuInfoDescService.getById(info.getSpuId());
            skuItemVo.setDesc(spuInfo);
        }, executor);

        CompletableFuture<Void> groupAttsFuture = infoFuture.thenAcceptAsync((info) -> {
            // 5 规格参数信息
            List<SpuItemAttrGroupVo> groupAtts = attrGroupService.getAttrGroupWithAttrsBySpuId(info.getSpuId(), info.getCatalogId());
            skuItemVo.setGroupAtts(groupAtts);
        }, executor);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            // 2 sku图片信息 pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            // 6 商品秒杀信息
            R r = seckillFeignService.skuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillSkuInfoVo seckillInfo = r.getData(new TypeReference<SeckillSkuInfoVo>() {
                });
                skuItemVo.setSeckillInfo(seckillInfo);
            }
        }, executor);

        // 等待所有任务完成
        CompletableFuture.allOf(infoFuture, saleAttrsFuture, spuInfoFuture, groupAttsFuture, imagesFuture, seckillFuture).get();

        return skuItemVo;
    }

}